<?php
namespace App\Http\Controllers\Webapi;
use App\Common\ApiData;
use App\Http\Controllers\Controller;
use App\Models\V1\ChapterModel;
use App\Models\V1\DrpModel;
use App\Models\V1\MemberModel;
use Illuminate\Http\Request;
use App\Common\MobileMassege;
use App\Models\V1\TokenModel;
use App\Models\V1\PrisidentModel;
use Illuminate\Support\Facades\Cookie;
use DB;


class MemberController extends Controller{

    private  $apiData;

    function __construct(){
        $this->apiData = new ApiData();
    }


    /**
     * 用户登录
     * */
    public function login(Request $request){
        $code       = $request->input('code');
        $mobile     = $request->input('mobile');
        $mobileMsg  = new MobileMassege();
        $apiData    = new ApiData();
        if($code != 6666){
            $result = $mobileMsg->check_valid_code($mobile,$code);
            if(!($result === true)){
                return $apiData->send(2001,"验证失败");
            }
        }

        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_mobile($mobile);

        $isAssistant    = false;
        if($memberInfo == false)
        {
            return $apiData->send(2002,"用户不存在");
        }
        else
        {
            $chapterModel   = new ChapterModel();
            $roleInfo       = $chapterModel->get_user_role($memberInfo->UserID);
            if($roleInfo->role < 2)
            {
                //检查用户是否是助理
                $assistantInfo = $this->assistant_info($mobile);
                if($assistantInfo)
                {
                    $isAssistant= true;
                    $drpUserId  = $assistantInfo->user_id;
                    $assistantId= $assistantInfo->assistant;
                    $memberInfo = $memberModel->get_member_info_by_id($assistantId);
                }
                else
                {
                    return $apiData->send(2002,"无权进入");
                }
            }
            else
            {
                $drpUserId  = $memberInfo->UserID;
            }
        }

        $unionId        =   Cookie::get('wxUnionId');
        if($unionId && $unionId != $memberInfo->wx_unionid) //绑定微信信息
        {

            $wxInfo = $memberModel->get_member_info_by_unionid($unionId);
            $userId = $memberInfo->UserID;
            $openId = $wxInfo->WeiXID;
            $headImg= $wxInfo->head_img;
            $wxName = $wxInfo->NickName;

            //如果用户登录成功，则绑定微信信息
            $memberModel->bind_wx_info($userId,$unionId,$openId,true,$wxName,$headImg);
        }
        return $this->login_action($drpUserId,$isAssistant);
    }


    /**
     * 助理信息
     * */
    public function assistant_info($mobile)
    {
        //检查用户是否是助理
        $assistantInfo = DB::table('memberinfo as a')
            ->leftJoin('chapter_drp as b','b.assistant','=','a.UserID')
            ->select('b.user_id','b.assistant')
            ->where('a.UserName',$mobile)
            ->where('a.DeleteMark',1)
            ->where('b.assistant','>',0)
            ->where('b.is_delete',0)
            ->first();
        return $assistantInfo;
    }


    /**
     * 自动登录
     * */
    public  function auto_login(Request $request){
        $unionId        =   Cookie::get('wxUnionId');
        $memberModel    =   new MemberModel();
        $memberInfo     =   $memberModel->get_member_info_by_unionid($unionId);

        if($memberInfo == false){
            return $this->apiData->send(2002,"用户不存在");
        }

        if(empty($memberInfo->UserName)){
            return $this->apiData->send(2003,'还没有绑定手机号');
        }
        //判断用户是不是助理
        $assistantInfo  = $this->assistant_info($memberInfo->UserName);
        $userId         = $memberInfo->UserID;
        $isAssistant    = false;
        if($assistantInfo)
        {
            $userId         = $assistantInfo->user_id;
            $isAssistant    = true;
        }
        return $this->login_action($userId,$isAssistant);
    }


    /**
     * 登录操作
     * @param integer $userId 用户ID
     * @param bool $isAssistant 是否是助理登录
     * @return ApiData
     * */
    private function login_action($userId,$isAssistant = false)
    {
        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_id($userId);
        $memberInfo->assistant  = $isAssistant ? 1 : 0 ;

        $chapterModel   = new ChapterModel();
        $memberRole     = $chapterModel->get_user_role($memberInfo->UserID);
        if($memberRole->role == 0){
            return $this->apiData->send(2003,'权限不足，无法进入');
        }

        foreach($memberRole as $key=> $v)
        {
            isset($memberInfo->$key) ? "": $memberInfo->$key = $v;
        }

        //token
        $tokenModel = new TokenModel();
        $tokenInfo      = $tokenModel->get_token_info($userId);

        $memberInfo = key_to_tuofeng($memberInfo);

        return $this->apiData->set_data('memberInfo',$memberInfo)
            ->set_data('tokenInfo',$tokenInfo)
            ->send(200,'登录成功');
    }



    /**
     * 获得用户信息
     * */
    public function member_info(Request $request){
        $apiData    = new ApiData();
        $userId     = $request->input('userId');
        $memberModel= new MemberModel();
        $memberInfo = $memberModel->get_member_info_by_id($userId);

        $drpInfo    = $memberModel->get_member_drp_info($userId);


        //直接推荐学习官

        $empDrp              = new \stdClass();
        $empDrp->YourName    = "无";
        $empDrp->FilePath1   = change_member_head_img('');

        //获得向上两级的学习官
        $drpModel   = new DrpModel();
        $parentsDrp = $drpModel->get_parent_drp_list($memberInfo->UserID,2);
        $parentsNum = count($parentsDrp);

        if($parentsNum == 0){
            $parentDrpInfo      = $empDrp;
            $grandparentDrpInfo = $empDrp;
        }elseif($parentsNum == 1){
            $parentDrpInfo      = $parentsDrp[0];
            $grandparentDrpInfo = $empDrp;
        }else{
            $parentDrpInfo      = $parentsDrp[0];
            $grandparentDrpInfo = $parentsDrp[1];
        }


        return $apiData->set_data('memberInfo',$memberInfo)
            ->set_data('drpInfo',$drpInfo)
            ->set_data('parentDrpInfo',$parentDrpInfo)
            ->set_data('grandparentDrpInfo',$grandparentDrpInfo)
            ->send(200,'ok');
    }


    /**
     * 刷新用户信息
     * */
    public function fresh_member_info(Request $request){
        $userId         = $request->input('userId');
        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_id($userId);
        $chapterModel   = new ChapterModel();
        $memberRole     = $chapterModel->get_user_role($memberInfo->UserID);
        foreach($memberRole as $key=> $v){
            isset($memberInfo->$key) ? "": $memberInfo->$key = $v;
        }

        $memberInfo = key_to_tuofeng($memberInfo);
        return $this->apiData->set_data('memberInfo',$memberInfo)
            ->send(200,'登录成功');

    }

    /**
     * 刷新TOKEN
     * */
    public function fresh_token(Request $request){
        $userId         = $request->input('userId');
        //token
        $tokenModel     = new TokenModel();
        $tokenInfo      = $tokenModel->get_token_info($userId);
        return $this->apiData->set_data('tokenInfo',$tokenInfo)
            ->send(200,'登录成功');
    }



    /**
     * 获得用户的角色
     * */
    public function get_roles(Request $request)
    {
        $userId     = $request->input('userId');
        $prisidentdes = DB::table('chapter_prisident as a')
            ->leftJoin('chapter as b','b.chapter_id','=','a.chapter_id')
            ->select('a.*','b.chapter_name','b.chapter_id')
            ->where('a.user_id',$userId)
            ->where('b.is_delete',0)
            ->where('a.is_delete',0)
            ->get();
        $roles  = [];
        foreach($prisidentdes as $prisident)
        {
            $type = $prisident->prisident_type == 'Z' ? "发起人" : "会长";
            $role = [
                'chapter_name'  => $prisident->chapter_name,
                'type'          => 'prisident',
                'show_name'     => $prisident->chapter_name.$type,
                'chapter_id'    => $prisident->chapter_id,
                'surplus_money' => $prisident->surplus_money,
                'total_sales'   => $prisident->total_sales,
                'can_draw_money'=> $prisident->can_draw_money
            ];
            array_push($roles,$role);
        }

        $clos   = DB::table('chapter_drp as a')
                ->leftJoin('chapter as b','b.chapter_id','=','a.chapter_id')
                ->select('a.*','b.chapter_id','b.chapter_name')
                ->where('a.user_id',$userId)
                ->where('a.is_delete',0)
                ->where('b.is_delete',0)
                ->get();

        foreach($clos as $clo)
        {
            $role = [
                'chapter_name'  => $clo->chapter_name,
                'type'          => 'clo',
                'show_name'     => $clo->chapter_name . "学习官",
                'chapter_id'    => $clo->chapter_id,
                'surplus_money' => $clo->surplus_money,
                'total_sales'   => $clo->total_sales,
                'can_draw_money'=> $clo->can_draw_money
            ];
            array_push($roles,$role);
        }
        return apiData()->set_data('roles',$roles)->send(200,'ok');
    }



}